package com.lntea.netty.reconnect;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

/**
 * Title: ReconnectServerHandler.java<br>
 * Description:  <br>
 * Copyright: Copyright (c) 2015<br>
 * Company: 北京云杉世界信息技术有限公司<br>
 *
 * @author lichao
 * @date 2019/11/12 11:59
 */
@ChannelHandler.Sharable
public class ReconnectServerHandler extends SimpleChannelInboundHandler<Object>{

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 正常情况下每隔5秒发送心跳消息
        // 可以强制关闭服务端进程，来测试客户端重连
        ctx.channel().eventLoop().scheduleAtFixedRate(() -> {
            ByteBuf buf = Unpooled.copiedBuffer("heart break", CharsetUtil.UTF_8);
            System.out.println("Server send heart break to client");
            ctx.writeAndFlush(buf);
        }, 0, 5, TimeUnit.SECONDS);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
        // discard
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
